﻿using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using LDSBusiness;
using LDSCore;
using LDSModel.Dal;
using LDSProject.Forms;
using LDSProject.Properties;

namespace LDSProject
{
    public partial class MainForm : Form
    {
        #region 窗体界面事件

        public MainForm()
        {
            InitializeComponent();


            //#if DEBUG
            //            UserService.Login("admin", Utils.EncryptMD5("000000"));
            //            Reload();
            //#else
            Login();
            //#endif
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            Text = Resources.ProjectName;
            lbVersion.Text = Resources.Version;
            lbCompany.Text = Resources.Company;

            MainConsole.Instance.Init(this);

            timer1.Start();
        }

        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            var result = MessageBox.Show(this, @"是否确定关闭软件?", @"警告", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
            if (DialogResult.Yes != result)
            {
                e.Cancel = true;
            }
            else
            {
                MainConsole.Instance.Stop();
            }
        }

        #endregion

        #region 界面更新

        public void Reload()
        {
            lbUserName.Text = string.Format("欢迎您,{0}{1}", UserService.CurrentUser.UserName, UserService.CurrentUser.IsManager == true ? "(管理员)" : string.Empty);
            label2.Text = UserService.CurrentUser.LastLoginTime.ToString();
            SetState("准备就绪");

            if (UserService.CurrentUser.IsManager != null && !UserService.CurrentUser.IsManager.Value)
            {
                btnSetting.Visible = false;
                btnOPLog.Visible = false;
                btnErrLog.Visible = false;
            }
            else
            {
                btnSetting.Visible = true;
                btnOPLog.Visible = true;
                //btnErrLog.Visible = true;
            }

            DeviceService.Instance.Refush();

            mapControl1.Initialization();
            areaControl1.Initialization();

            MainConsole.Instance.Start(this);

            Show();
        }

        private void Button_MouseEnter(object sender, EventArgs e)
        {
            var button = (Button)sender;
            button.BackgroundImage = Resources.BtnBackOn;
        }

        private void Button_MouseLeave(object sender, EventArgs e)
        {
            var button = (Button)sender;
            button.BackgroundImage = Resources.BtnBack;
        }

        #endregion

        #region 用户管理

        /// <summary>
        /// 弹出登陆界面
        /// </summary>
        private void Login()
        {
            Hide();
            var loginForm = new LoginForm(this);
            loginForm.ShowDialog(this);
        }

        /// <summary>
        /// 弹出修改密码
        /// </summary>
        private void llbPassword_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            var dialog = new ModifyPasswordForm();
            dialog.ShowDialog(this);
        }

        /// <summary>
        /// 注销当前用户
        /// </summary>
        private void llbLogout_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            if (DialogResult.Yes == MessageBox.Show(this, @"是否注销当前用户?", @"警告", MessageBoxButtons.YesNo, MessageBoxIcon.Warning))
            {
                MainConsole.Instance.Stop();
                Login();
            }
        }

        #endregion

        #region 功能点击

        private void btnSyncTime_Click(object sender, EventArgs e)
        {
            if (!MainConsole.Instance.CheckPortIsOpen(this)) return;
            var result = MessageBox.Show(this, Resources.IsSyncAllTime, @"提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question);

            if (result != DialogResult.Yes) return;
            var addressList = Enumerable.ToList(DeviceService.Instance.DeviceList.Select(device => device.Address != null ? device.Address.Value : 0));

            var returnInfo = new StringBuilder();
            var dialog = new CmdProcessForm(addressList, MsgType.ZGCMD_SET_SYSTIME, "全网时间同步", ref returnInfo);
            dialog.ShowDialog(this);
            SetState(returnInfo.ToString());
        }

        private void btnQuery_Click(object sender, EventArgs e)
        {
            var dialog = new QueryForm(Guid.NewGuid());
            dialog.ShowDialog(this);
        }

        private void btnSetting_Click(object sender, EventArgs e)
        {
            var dialog = new UserManageForm();
            dialog.ShowDialog(this);
        }

        private void btnLog_Click(object sender, EventArgs e)
        {
            var dialog = new OpLogForm();
            dialog.ShowDialog(this);
        }

        private void btnErr_Click(object sender, EventArgs e)
        {
            var dialog = new ErrorLogForm(this);
            dialog.ShowDialog(this);
        }

        #endregion

        public void SetState(string info)
        {
            toolStripStatusLabel3.Text = info;
        }

        private void btnEnablePort_Click(object sender, EventArgs e)
        {
            if (DataRecipient.Instance.IsOpen)
            {
                DialogResult result = MessageBox.Show(this, string.Format("是否关闭监测端口({0})?", DataRecipient.Instance.PortName), @"警告", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);

                if (result == DialogResult.Yes)
                {
                    MainConsole.Instance.Stop();
                    btnEnablePort.Image = Resources.close;
                    端口设置ToolStripMenuItem.Enabled = true;
                    端口设置ToolStripMenuItem.ToolTipText = string.Empty;
                    toolStripStatusLabel3.Text = string.Format("监测端口({0})已关闭.", DataRecipient.Instance.PortName);
                }
            }
            else
            {
                if (MainConsole.Instance.Start(this))
                {
                    btnEnablePort.Image = Resources.open;
                    端口设置ToolStripMenuItem.Enabled = false;
                    端口设置ToolStripMenuItem.ToolTipText = @"请关闭当前串口后设置";
                    toolStripStatusLabel3.Text = string.Format("监测端口({0})已打开.", DataRecipient.Instance.PortName);
                }
            }
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            if (DataRecipient.Instance.IsOpen)
            {
                if (btnEnablePort.Image != Resources.open || 端口设置ToolStripMenuItem.Enabled)
                {
                    btnEnablePort.Image = Resources.open;
                    端口设置ToolStripMenuItem.Enabled = false;
                    端口设置ToolStripMenuItem.ToolTipText = @"请关闭当前串口后设置";
                }
            }
            else
            {
                if (btnEnablePort.Image != Resources.close || 端口设置ToolStripMenuItem.Enabled != true)
                {
                    btnEnablePort.Image = Resources.close;
                    端口设置ToolStripMenuItem.Enabled = true;
                    端口设置ToolStripMenuItem.ToolTipText = string.Empty;
                }
            }
        }

        private void 组网图ToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            var dialog = new NetInfoForm();
            dialog.ShowDialog(this);
        }

        private void 退出QToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void 端口设置ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var dialog = new PortConfigForm();
            dialog.ShowDialog();
        }

        private void 操作手册ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var p = new Process
                {
                    StartInfo = new ProcessStartInfo(Path.Combine(Application.StartupPath, "雷电监测系统操作手册.chm"))
                };
            p.Start();
        }

        private void 时间同步ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var dialog = new SyncTimeSetForm();
            dialog.ShowDialog();
        }
    }
}
